package com.wisdom.benefit.jufa.widget;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.AttrRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.utils.DisplayUtil;
import com.wisdom.benefit.jufa.utils.EditTextHelper;

import java.util.Objects;

/**
 * 验证码布局
 * Created by zhoudawei on 2017/6/29.
 */

public class CodeLayout extends FrameLayout {

    private AppCompatTextView mTitleView;
    private AppCompatEditText mEditText;
    private AppCompatTextView mButtonView;

    private CountDownTimer mTimer;//用来实现倒计时

    private TextWatcher mTextWatcher;
    private onGetCodeViewClickListener mOnGetCodeViewClickListener;

    public CodeLayout(@NonNull Context context) {
        this(context, null);
    }

    public CodeLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CodeLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.layout_code_view, this, true);
        mTitleView = findViewById(R.id.title_sms_code);
        mEditText = findViewById(R.id.et_sms_code);
        mButtonView = findViewById(R.id.tv_get_sms_code);
        init();
    }

    private void init() {
        EditTextHelper.getEditTextDeleteIconWrapper(mEditText).setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (mTextWatcher != null)
                    mTextWatcher.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mTextWatcher != null)
                    mTextWatcher.onTextChanged(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 6)
                    mEditText.setSelection(s.length());
                if (!TextUtils.isEmpty(s.toString()) && s.length() > 6)
                    mEditText.setText(s.toString().substring(0, 6));
                if (mTextWatcher != null)
                    mTextWatcher.afterTextChanged(s);
            }
        });

        mButtonView.setText(R.string.get_sms_code);
        mButtonView.setOnClickListener(v -> {
            if (mOnGetCodeViewClickListener != null)
                mOnGetCodeViewClickListener.onGetCodeViewClick(v);
        });
    }

    public void setGetCodeEnabled(boolean enabled) {
        mButtonView.setTextColor(enabled ?
                ContextCompat.getColor(getContext(), R.color.blue_3586f9) :
                ContextCompat.getColor(getContext(), R.color.gray_999999));
        mButtonView.setEnabled(enabled);
    }

    public void startCountDown() {
        setGetCodeEnabled(false);
        final StringBuilder sb = new StringBuilder();
        if (mTimer == null) {
            mTimer = new CountDownTimer(1000L * 60, 1000L) {
                @Override
                public void onTick(long millisUntilFinished) {
                    setGetCodeEnabled(false);
                    int count = (int) (millisUntilFinished / 1000L);
                    sb.delete(0, sb.length());
                    sb.append("重新发送").append("(").append(count).append("s").append(")");
                    mButtonView.setText(sb.toString());
                }

                @Override
                public void onFinish() {
                    stopCountDown();
                }
            };
        }
        mTimer.start();
    }

    public void stopCountDown() {
        if (mTimer != null) {
            mTimer.cancel();
            setGetCodeEnabled(true);
            mButtonView.setText("重新发送");
        }
    }

    public String getCode() {
        return Objects.requireNonNull(mEditText.getText()).toString();
    }

    /**
     * 设置 TitleView 宽度，单位dp
     *
     * @param width 宽度
     */
    public void setTitleViewWidth(int width) {
        ViewGroup.LayoutParams layoutParams = mTitleView.getLayoutParams();
        layoutParams.width = DisplayUtil.dip2px(mTitleView.getContext(), width);
        mTitleView.setLayoutParams(layoutParams);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void setTextWatcher(TextWatcher textWatcher) {
        mTextWatcher = textWatcher;
    }

    public void setOnGetCodeViewClickListener(onGetCodeViewClickListener listener) {
        mOnGetCodeViewClickListener = listener;
    }

    public interface onGetCodeViewClickListener {
        void onGetCodeViewClick(View view);
    }
}
